<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :width="1400">
    <div class="mb-8px" v-if="!formtype.includes('lookup')">
      <el-button type="primary" @click="addLine">新增行</el-button>
      <el-button @click="submitForm" type="primary" :disabled="loading">保存</el-button>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </div>
    <el-table
      ref="multipleTableRef"
      v-loading="loading"
      :max-height="450"
      :data="craftBookData"
      border
    >
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column label="文件名称" align="center" width="200">
        <template #default="scope">
          <div v-if="scope.row.fileList">
            <UploadFileAdd
              v-model="scope.row.fileList"
              :isShowTip="false"
              :limit="1"
              :fileSize="200"
              :fileType="['pdf', 'png', 'jpg']"
              :index="scope.$index"
              @click="uploadFile(scope.$index)"
              @update:modelValue="uploadFileRes"
            />
          </div>
          <div v-else-if="scope.row.editData.includes('edit')">{{ scope.row.fileName }}</div>
          <div v-else><el-input v-model="scope.row.fileName" /></div>
          <!-- <el-input v-model="scope.row.fileName" /> -->
        </template>
      </el-table-column>
      <el-table-column label="文件类型" align="center" prop="fileType" />
      <el-table-column label="文件大小" align="center" prop="fileSize" />
      <el-table-column label="版本号" align="center" prop="version">
        <template #default="scope">
          <div v-if="scope.row.editData.includes('edit')">{{ scope.row.version }}</div>
          <div v-else><el-input v-model="scope.row.version" /></div>
        </template>
      </el-table-column>
      <el-table-column label="启用日期" align="center" width="200">
        <template #default="scope">
          <div v-if="scope.row.editData.includes('edit')">
            {{ scope.row.enableTime }}
          </div>
          <div v-else>
            <el-date-picker
              @change="dateEnableTime(scope.row, scope.$index)"
              v-model="scope.row.enableTime"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="选择启用日期"
              class="!w-160px"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="停用日期" align="center" width="200">
        <template #default="scope">
          <div v-if="scope.row.editData.includes('edit')">
            {{ scope.row.stopTime }}
          </div>
          <div v-else>
            <el-date-picker
              @change="dateStopTime(scope.row)"
              v-model="scope.row.stopTime"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="选择停用日期"
              class="!w-160px"
            />
          </div>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="creatorName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="!formtype.includes('lookup')"
        label="操作"
        header-align="center"
        align="right"
        width="120"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            v-if="!scope.row.editData.includes('show')"
            link
            type="primary"
            @click="editLine(scope.row)"
            >编辑</el-button
          >
          <el-button link type="danger" @click="removeLine(scope.$index, scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="mb-20px">
      <el-pagination
        v-model:current-page="queryParams.pageNo"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[50, 100, 150, 200, 250]"
        :background="true"
        class="float-right mt-5px mb-20px"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </Dialog>
</template>
<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import * as CraftTaskBillApi from '@/api/config/craftTaskBill'
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('作业指导书') // 弹窗的标题
const loading = ref(false) // 表单的加载中
const total = ref(0) // 列表的总页数
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const queryParams = reactive({
  pageNo: 1,
  pageSize: 50
})
const craftBookData: any = ref([]) // 表单数据

const taskId = ref()
const taskDict = ref()
const formtype = ref()
/** 打开弹窗 */
const open = async (dict, typeData, id?: number) => {
  taskId.value = id
  taskDict.value = dict
  formtype.value = typeData
  dialogVisible.value = true

  // 修改时，设置数据
  loading.value = true
  try {
    let params = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      dictProcessName: dict.dictProcessName,
      partName: dict.partName,
      productNumber: dict.productNumber
    }
    const data = await CraftTaskBillApi.getCraftCourseBook(params)
    total.value = data.total
    craftBookData.value = data.list.map((item) => {
      item.editData = 'edit'
      return item
    })
  } finally {
    loading.value = false
  }
}

/**启用时间选择判断 */
const dateEnableTime = (val, index) => {
  if (craftBookData.value.length > 1) {
    const stopDate = new Date(craftBookData.value[index - 1].stopTime)
    const enableDate = new Date(val.enableTime)
    if (stopDate.getTime() > enableDate.getTime()) {
      val.enableTime = ''
      message.notifyError('版本的启用日期必须大于上个版本的停用日期!')
    }
  }
}
/**停用时间选择判断 */
const dateStopTime = (row) => {
  const enableDate = new Date(row.enableTime)
  const stopDate = new Date(row.stopTime)
  if (enableDate.getTime() > stopDate.getTime()) {
    row.stopTime = ''
    message.notifyError('停用日期必须大于启用日期!')
  }
}

/**新增行 */
const addLine = () => {
  let data = {
    fileName: '',
    fileType: '',
    fileSize: '',
    version: '',
    enableTime: '',
    stopTime: '',
    creatorName: '',
    createTime: '',
    editData: 'show',
    fileList: []
  }
  craftBookData.value.push(data)
}

/**删除行 */
const removeLine = async (index, id?: number) => {
  craftBookData.value.splice(index, 1)
  if (id) {
    await CraftTaskBillApi.deleteCraftBillFile(id)
  }
}

// 编辑
const editLine = (row) => {
  row.editData = ''
}
const changeIndex = ref(0)
/**上传附件 */
const uploadFile = (index) => {
  changeIndex.value = index
}
/**文件上传返回 */
const uploadFileRes = async (data) => {
  if (JSON.parse(data).length) {
    const res = JSON.parse(data)
    craftBookData.value[changeIndex.value].filePath = res[0].url
    craftBookData.value[changeIndex.value].fileName = res[0].name
    craftBookData.value[changeIndex.value].fileType = res[0].type
    craftBookData.value[changeIndex.value].fileSize = res[0].size
  } else {
    craftBookData.value[changeIndex.value].fileList = []
    craftBookData.value[changeIndex.value].filePath = ''
    craftBookData.value[changeIndex.value].fileName = ''
  }
}

/** 保存 */
const submitForm = async () => {
  loading.value = true
  try {
    if (craftBookData.value.length === 0) {
      return message.notifyError('请选择文件上传')
    }
    // craftBookData.value.forEach((item) => {
    //   delete item.editData
    // })
    const data = {
      updateList: craftBookData.value,
      dictProcessName: taskDict.value.dictProcessName,
      partName: taskDict.value.partName,
      productNumber: taskDict.value.productNumber
    }
    await CraftTaskBillApi.createCraftTaskFile(data)
    // 发送操作成功的事件
    emit('success', craftBookData.value.length)
    dialogVisible.value = false
    message.success(t('common.updateSuccess'))
  } finally {
    loading.value = false
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 页面容量 */
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  open(taskDict.value, formtype.value, taskId.value)
}
/** 页面 */
const handleCurrentChange = (val: number) => {
  queryParams.pageNo = val
  open(taskDict.value, formtype.value, taskId.value)
}
</script>
